package com.hsgene.sample.service.impl;


import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.UsedAmont;
import com.hsgene.common.util.code.CodeCreat;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.sample.condition.SampleCondition;
import com.hsgene.sample.constants.TypeLabel;
import com.hsgene.sample.domain.GeneticTestingSample;
import com.hsgene.sample.dto.GeneticTestingAgencySampleDto;
import com.hsgene.sample.dto.GeneticTestingSampleDto;
import com.hsgene.sample.exception.SampleErrorCode;
import com.hsgene.sample.persistence.GeneticTestingOrgSampleRepository;
import com.hsgene.sample.persistence.GeneticTestingSampleMapper;
import com.hsgene.sample.service.SampleService;
import com.hsgene.sample.service.api.GeneratorService;
import com.hsgene.sample.service.api.ProductService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:样笨管理
 * @author: fuxiang
 * @date: 2018/8/14 14:25
 */
@Service
public class SampleServiceImpl  implements SampleService {
    public static final String HS_0001 = "HS0001";
    public static final String HS = "HS";
    @Resource
    private GeneticTestingOrgSampleRepository sampleRepository;
    @Resource
    private GeneratorService generatorService;
    @Resource
    private ProductService productService;
    @Resource
    private GeneticTestingSampleMapper sampleMapper;


    @Override
    public ApiResult<Pagination<GeneticTestingSampleDto>> queryList(SampleCondition condition) {
        int totalCount = sampleMapper.getCount(condition);
        Pagination<GeneticTestingSampleDto> pagination = Pagination.newInstance(condition.getLimitHelper(), totalCount);
        if (totalCount > 0) {
            List<GeneticTestingSample> sampleDtoList = sampleMapper.queryList(condition);
            int rowNumber = (condition.getLimitHelper().getPage() - 1) * condition.getLimitHelper().getSize();
            List<GeneticTestingSampleDto> sampleDtos = new ArrayList<>();
            for (int i = 0, n = sampleDtoList.size(); i < n; i++) {
                GeneticTestingSample geneticTestingSample = sampleDtoList.get(i);
                GeneticTestingSampleDto geneticTestingSampleDto = new GeneticTestingSampleDto();
                BeanUtils.copyProperties(geneticTestingSample,geneticTestingSampleDto);
                if(TypeLabel.LABEL.getDesc().equals(condition.getTypeLabel())){
                    GeneticTestingSample geneticTestingSample1 = sampleMapper.selectByPrimaryKey(geneticTestingSample.getParentId());
                    geneticTestingSampleDto.setParentName(geneticTestingSample1.getLabel());
                    geneticTestingSampleDto.setLabelKey(geneticTestingSample1.getLabelKey());
                    geneticTestingSampleDto.setLabelDescription(geneticTestingSample1.getLabelDescription());
                 }
                geneticTestingSampleDto.setNumber(rowNumber + i + 1);
                sampleDtos.add(geneticTestingSampleDto);
            }
            pagination.setResult(sampleDtos);
        } else {
            pagination.setResult(new ArrayList<>());
        }
        return ApiResult.succ(pagination);
    }

    @Override
    public ApiResult<NullObject> insertSampleDto(GeneticTestingSample geneticTestingSample) {
        FieldChecker.checkEmpty(geneticTestingSample, "geneticTestingSample");
        geneticTestingSample.setCreateDateTime(new Date());
        geneticTestingSample.setUpdateDateTime(geneticTestingSample.getCreateDateTime());
        geneticTestingSample.setAmount(0);
        geneticTestingSample.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        ApiResult<GeneratorDto> sample = generatorService.getGenerator(null, null);
        if (!sample.isSucc()) {
            return ApiResult.fail(sample.getError());
        }
        String id = sample.getData().getSerialNumber();
        geneticTestingSample.setId(id);
        if(!StringUtils.isEmpty(geneticTestingSample.getParentId())){
            updateIsUsedAmount(geneticTestingSample.getParentId(),UsedAmont.ADD.getIdentifier());
        }
        //增加样本code
        String sampleCode=sampleMapper.selectOrderByCode();
        if(StringUtils.isEmpty(sampleCode)){
            geneticTestingSample.setSampleCode(HS_0001);
        }else{
            String code = CodeCreat.getCode(sampleCode,HS);
            geneticTestingSample.setSampleCode(code);
        }

        int i = sampleMapper.insertSelective(geneticTestingSample);
        if (i > 0) {
            return ApiResult.succ();
        }
        return ApiResult.fail(SampleErrorCode.OPERATION_FAILED);
    }



    @Override
    public ApiResult<NullObject> updateSampleDto(GeneticTestingSample geneticTestingSample) {
        if (StringUtils.isEmpty(geneticTestingSample.getId())) {
            ApiResult.fail(SampleErrorCode.PRIMARY_KEY_CANNOT_BE_EMPTY);
        }
        Date date = new Date();
        geneticTestingSample.setUpdateDateTime(date);
        if(StringUtils.isNotEmpty(geneticTestingSample.getParentId())){
            GeneticTestingSample geneticTestingSample1= sampleMapper.selectByPrimaryKey(geneticTestingSample.getId());
            if(!geneticTestingSample1.getId().equals(geneticTestingSample.getParentId())){
                updateIsUsedAmount(geneticTestingSample.getParentId(),UsedAmont.ADD.getIdentifier());
                updateIsUsedAmount(geneticTestingSample1.getId(),UsedAmont.REDUCE.getIdentifier());
            }
        }
        sampleMapper.updateByPrimaryKey(geneticTestingSample);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<NullObject> deleteSampleDto(GeneticTestingSample geneticTestingSample) {
        geneticTestingSample.setDeleteFlag(1);
        sampleMapper.updateByPrimaryKeySelective(geneticTestingSample);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<GeneticTestingSampleDto> queryById(String id,String typeLabel) {
        GeneticTestingSample geneticTestingSample = sampleMapper.selectByPrimaryKey(id);
        GeneticTestingSampleDto geneticTestingSampleDto = new GeneticTestingSampleDto();
        BeanUtils.copyProperties(geneticTestingSample,geneticTestingSampleDto);
        if(TypeLabel.LABEL.getDesc().equals(typeLabel)){
            GeneticTestingSample geneticTestingSample1 = sampleMapper.selectByPrimaryKey(geneticTestingSample.getParentId());
            geneticTestingSampleDto.setParentName(geneticTestingSample1.getLabel());
            geneticTestingSampleDto.setParentLabelKey(geneticTestingSample1.getLabelKey());
        }
        return ApiResult.succ(geneticTestingSampleDto);
    }

    @Override
    public ApiResult<NullObject> updateSampleDtoMore(List<GeneticTestingAgencySampleDto> sampleDtoList) {
        if (sampleDtoList == null || sampleDtoList.isEmpty()) {
            ApiResult.fail(SampleErrorCode.OBJECT_IS_EMPTY);
        }
        //TODO 暂时不用了
       /* for (GeneticTestingAgencySampleDto sampleDto : sampleDtoList) {
            ApiResult<NullObject> nullObjectApiResult = updateSampleDto(sampleDto);
            if (nullObjectApiResult.getCode() != 200) {
                return ApiResult.fail(SampleErrorCode.OPERATION_FAILED);
            }
        }*/
        return ApiResult.succ();
    }

    @Override
    public ApiResult<List<GeneticTestingSampleDto>> getAll(SampleCondition condition) {
        List<GeneticTestingSample> geneticTestingOrgSampleDtos = sampleMapper.getAll( condition);
        List<GeneticTestingSampleDto> label = geneticTestingOrgSampleDtos.stream().map(c -> {
            GeneticTestingSampleDto geneticTestingSampleDto = new GeneticTestingSampleDto();
            BeanUtils.copyProperties(c, geneticTestingSampleDto);
            if (condition.getTypeLabel().equals("label")) {
                GeneticTestingSample geneticTestingSample1 = sampleMapper.selectByPrimaryKey(c.getParentId());
                geneticTestingSampleDto.setParentName(geneticTestingSample1.getLabel());
            }
            return geneticTestingSampleDto;
        }).collect(Collectors.toList());
        return ApiResult.succ(label);
    }

    @Override
    public ApiResult<String> getByids(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return ApiResult.fail(SampleErrorCode.PRIMARY_KEY_CANNOT_BE_EMPTY);
        }
        String[] split = ids.split(",");
        List<GeneticTestingAgencySampleDto> sampleDtoList = sampleRepository.getByids(split);
        StringBuilder stringBuilder = new StringBuilder();
        sampleDtoList.forEach(c -> stringBuilder.append(",").append(c.getName()));
        String s = stringBuilder.deleteCharAt(0).toString();
        return ApiResult.succ(s);
    }

    @Override
    public ApiResult<NullObject> deleteSampleDtoMore( List<GeneticTestingSample> sampleList) {
        if (sampleList == null || sampleList.isEmpty()) {
            return ApiResult.fail(SampleErrorCode.OBJECT_IS_EMPTY);
        }
        sampleMapper.deleteMore(sampleList);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<NullObject> updateSampleUsed(String sampleDto) {
        if ( StringUtils.isEmpty(sampleDto)) {
            return ApiResult.fail(SampleErrorCode.PRIMARY_KEY_CANNOT_BE_EMPTY);
        }
        int i=sampleRepository.updateSampleUsed(sampleDto);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<List<GeneticTestingSampleDto>> getSamplesByids(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return ApiResult.fail(SampleErrorCode.PRIMARY_KEY_CANNOT_BE_EMPTY);
        }
        String[] split = ids.split(",");
        List<GeneticTestingSample> sampleDtoList = sampleMapper.getByids(split);
        List<GeneticTestingSampleDto> collect = sampleDtoList.stream().map(c -> {
            GeneticTestingSampleDto geneticTestingSampleDto = new GeneticTestingSampleDto();
            BeanUtils.copyProperties(c, geneticTestingSampleDto);
            GeneticTestingSample geneticTestingSample = sampleMapper.selectByPrimaryKey(c.getParentId());
            geneticTestingSampleDto.setParentName(geneticTestingSample.getLabel());
            geneticTestingSampleDto.setLabelKey(geneticTestingSample.getLabelKey());
            geneticTestingSampleDto.setLabelDescription(geneticTestingSample.getLabelDescription());
            return geneticTestingSampleDto;
        }).collect(Collectors.toList());
        return ApiResult.succ(collect);
    }

    @Override
    public ApiResult updateIsUsedAmount(String id, String type) {
        if(StringUtils.isEmpty(type)){
            return ApiResult.fail(SampleErrorCode.TYPECAN_NOT_BE_EMPTY);
        }
        GeneticTestingSample geneticTestingSample = new GeneticTestingSample();
        geneticTestingSample.setId(id);
        GeneticTestingSample geneticTestingSample1 = sampleMapper.selectByPrimaryKey(id);
        if(geneticTestingSample1==null){
            return ApiResult.fail(SampleErrorCode.OBJECT_IS_EMPTY);
        }
        if(UsedAmont.ADD.getIdentifier().equals(type)){
            geneticTestingSample.setAmount(geneticTestingSample1.getAmount()+1);
        }else if(UsedAmont.REDUCE.getIdentifier().equals(type)){
            if (geneticTestingSample1.getAmount()==0) {
              return ApiResult.succ();
            }else{
                geneticTestingSample.setAmount(geneticTestingSample1.getAmount()-1);
            }
        }
        sampleMapper.updateByPrimaryKeySelective(geneticTestingSample);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<NullObject> deleteSampleType(GeneticTestingAgencySampleDto genetictestingagencysampledto) {

        return null;
    }

    @Override
    public GeneticTestingSample getByLabel(String label,String typeLabel) {
        GeneticTestingSample geneticTestingSample= sampleMapper.getByLabel(label, typeLabel);
        return geneticTestingSample;
    }

    @Override
    public GeneticTestingSample getByIdAndNoDelete(String id) {
        GeneticTestingSample geneticTestingSample=sampleMapper.getByIdAndNoDelete(id);
        return geneticTestingSample;
    }


}
